<template>
  <div class="home-user-info-container">
    <el-card class="box-card" shadow="hover">
      <div>
        <el-row :gutter="20">
          <!-- <el-col :span="2">
            <div class="div-avatar">
              <img :src="userInfo.avatar" class="home-user-avatar" />
            </div>
          </el-col> -->
          <el-col :span="22">
            <div class="user-info-header">
              欢迎回来<router-link to="/user/profile">{{
                userInfo.nickName
              }}</router-link>
            </div>
            <div class="user-info-detail">
              <i class="el-icon-time">
                上次登录时间<span>{{ userInfo.lastLoginTime }}</span></i
              >
              <i class="el-icon-map-location">
                上次登录IP<span
                  >{{ userInfo.lastLoginIp }} [
                  {{ userInfo.lastLoginAddr }} ]</span
                ></i
              >
              <i></i>
            </div>
          </el-col>
        </el-row>
      </div>
    </el-card>
    <el-dialog
      :close-on-press-escape="false"
      title="完善企业账号信息"
      :visible.sync="open"
      width="70%"
      :showClose="false"
      v-dialogDrag
      append-to-body
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="170px">
        <el-steps :active="active" finish-status="success" align-center>
          <el-step title="步骤 1" description="当前企业账号所属角色"></el-step>
          <el-step title="步骤 2" description="完善企业信息"></el-step>
          <!-- <el-step title="步骤 3"></el-step> -->
        </el-steps>
        <el-card class="box-card" shadow="hover">
          <div slot="header" class="clearfix">
            <span
              ><el-alert
                title="UKey首次登录，需要完善以下企业信息"
                type="error"
                :closable="false"
              ></el-alert
            ></span>
            <!-- <el-button style="float: right; padding: 3px 0" type="text">操作按钮</el-button> -->
          </div>

          <div v-if="active === 0">
            <!-- <el-divider>企业类型</el-divider> -->
            <el-form-item label="企业类型" prop="roleIds">
              <el-select
                v-model="form.roleIds"
                multiple
                clearable
                style="width: 50%"
                placeholder="选择企业类型，可多选"
              >
                <el-option
                  v-for="dict in dict.type.biz_organization_role_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="parseInt(dict.value)"
                ></el-option>
              </el-select>
            </el-form-item>
          </div>
          <div v-if="active === 1">
            <!-- <el-divider>企业信息</el-divider> -->
            <el-row>
              <el-col :span="12">
                <el-form-item label="企业名称1" prop="organizationName">
                  <el-input
                    disabled
                    v-model="form.organizationName"
                    placeholder="请输入企业名称"
                    maxlength="64"
                    show-word-limit
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="统一社会信用代码" prop="organizationCode">
                  <el-input
                    v-model="form.organizationCode"
                    disabled
                    placeholder="请输入统一社会信用代码"
                    maxlength="10"
                    show-word-limit
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="工商营业执照注册号" prop="licenseNum">
                  <el-input
                    v-model="form.licenseNum"
                    placeholder="请输入工商营业执照注册号"
                    maxlength="64"
                    show-word-limit
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="企业营业地址" prop="address">
                  <el-input
                    v-model="form.address"
                    placeholder="请输入企业营业地址"
                    maxlength="255"
                    show-word-limit
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="企业营业地址邮政编码" prop="postalCode">
                  <el-input
                    v-model="form.postalCode"
                    placeholder="请输入企业营业地址邮政编码"
                    maxlength="6"
                    show-word-limit
                    :rules="[
                      {
                        pattern: /^[1-9]\d*$/,
                        message: '请输入大于0的整数',
                        trigger: 'change',
                      },
                    ]"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="法定代表人姓名" prop="legalMan">
                  <el-input
                    v-model="form.legalMan"
                    placeholder="请输入法定代表人姓名"
                    maxlength="10"
                    show-word-limit
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="法定代表人证件号码" prop="legalManIdcard">
                  <el-input
                    v-model="form.legalManIdcard"
                    placeholder="请输入法定代表人证件号码"
                    maxlength="18"
                    show-word-limit
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="法定代表人职务" prop="legalManDuty">
                  <el-input
                    v-model="form.legalManDuty"
                    placeholder="请输入法定代表人职务"
                    maxlength="10"
                    show-word-limit
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="法定代表人职称" prop="legalManProtitle">
                  <el-input
                    v-model="form.legalManProtitle"
                    placeholder="请输入法定代表人职称"
                    maxlength="10"
                    show-word-limit
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="注册资本(万元)" prop="regprin">
                  <el-input
                    v-model="form.regprin"
                    placeholder="请输入注册资本(万元)"
                    maxlength="5"
                    show-word-limit
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="实收资金(万元)" prop="factRegprin">
                  <el-input
                    v-model="form.factRegprin"
                    placeholder="请输入实收资金(万元)"
                    maxlength="5"
                    show-word-limit
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="成立日期" prop="corpbirthDate">
                  <el-date-picker
                    clearable
                    v-model="form.corpbirthDate"
                    type="date"
                    value-format="yyyy-MM-dd"
                    placeholder="请选择成立日期"
                    :picker-options="dateRangePicker"
                  >
                  </el-date-picker>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="办公电话" prop="officePhone">
                  <el-input
                    v-model="form.officePhone"
                    placeholder="请输入办公电话"
                    maxlength="15"
                    show-word-limit
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="传真号码" prop="fax">
                  <el-input v-model="form.fax" placeholder="请输入传真号码" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="联系人姓名" prop="linkMan">
                  <el-input
                    v-model="form.linkMan"
                    placeholder="请输入联系人姓名"
                    maxlength="10"
                    show-word-limit
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="联系人办公电话" prop="linkTel">
                  <el-input
                    v-model="form.linkTel"
                    placeholder="请输入联系人办公电话"
                    maxlength="15"
                    show-word-limit
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="联系人手机号码" prop="linkPhone">
                  <el-input
                    v-model="form.linkPhone"
                    placeholder="请输入联系人手机号码"
                    maxlength="11"
                    show-word-limit
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="联系邮箱" prop="email">
                  <el-input
                    v-model="form.email"
                    placeholder="请输入联系邮箱"
                    maxlength="50"
                    show-word-limit
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="企业网址" prop="url">
                  <el-input
                    v-model="form.url"
                    placeholder="请输入企业网址"
                    maxlength="90"
                    show-word-limit
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="企业净资产" prop="assets">
                  <el-input
                    v-model="form.assets"
                    placeholder="请输入企业净资产"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="经营范围" prop="businesssCope">
                  <el-input
                    v-model="form.businesssCope"
                    placeholder="请输入经营范围"
                    maxlength="255"
                    show-word-limit
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </div>
          <div v-if="active === 2">
            <el-result icon="success" title="填写成功" subTitle="">
              <template slot="extra">
                <el-button type="danger" center="true" @click="submitForm" round
                  >进入系统</el-button
                >
              </template>
            </el-result>
          </div>
        </el-card>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button
          style="margin-top: 12px"
          :disabled="active === 0"
          type="primary"
          plain
          icon="el-icon-arrow-left"
          @click="previous"
          >上一步</el-button
        >
        <el-button
          style="margin-top: 12px"
          :disabled="active === 2"
          type="primary"
          plain
          @click="next"
          >下一步<i class="el-icon-arrow-right el-icon--right"></i
        ></el-button>
      </div>
    </el-dialog>

    <el-dialog
      :close-on-press-escape="false"
      title="完善主管部门账号信息"
      :visible.sync="deptOpen"
      width="70%"
      :showClose="false"
      v-dialogDrag
      append-to-body
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="170px">
        <el-form-item label="主管部门所在地" prop="deptId">
          <treeselect
            v-model="form.deptId"
            :options="deptOptions"
            :show-count="true"
            placeholder="请选择主管部门所在地"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitDeptAuthRoleForm"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { getHomeUserInfo } from "@/api/system/user";
import {
  unPermissionAuthRole,
  unPermissionDeptAuthRole,
} from "@/api/system/user";
import { updateCompany } from "@/api/hades/organization/company";
import { deptTreeSelect } from "@/api/system/dept";

import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "UserInfoDashboard",
  dicts: ["biz_organization_role_type"],
  components: { Treeselect },
  data() {
    return {
      userInfo: {},
      open: false,
      deptOpen: false,
      // 部门树选项
      deptOptions: undefined,
      form: {},
      rules: {
        deptId: [
          {
            required: true,
            message: "主管部门所在地不能为空",
            trigger: "blur",
          },
        ],
        roleIds: [
          { required: true, message: "企业类型不能为空", trigger: "blur" },
        ],
        organizationName: [
          { required: true, message: "企业名称不能为空", trigger: "blur" },
        ],
        organizationCode: [
          {
            required: true,
            message: "统一社会信用代码不能为空",
            trigger: "blur",
          },
        ],
        licenseNum: [
          {
            required: true,
            message: "工商营业执照注册号不能为空",
            trigger: "blur",
          },
        ],
        address: [
          { required: true, message: "企业营业地址不能为空", trigger: "blur" },
        ],
        legalMan: [
          {
            required: true,
            message: "法定代表人姓名不能为空",
            trigger: "blur",
          },
          {
            pattern: /^[\u4e00-\u9fa5]{2,6}$/,
            message: "法定代表人姓名只能用汉字,长度2-4位",
            trigger: "change",
          },
        ],
        legalManIdcard: [
          {
            required: true,
            message: "法定代表人证件号码不能为空",
            trigger: "blur",
          },
          {
            pattern: /^(\d{15}$|^\d{18}$|^\d{17}(\d|X))$/,
            message: "请输入正确的身份证号,末尾若为X请大写",
            trigger: "change",
          },
        ],
        corpbirthDate: [
          { required: true, message: "成立日期不能为空", trigger: "blur" },
        ],
        officePhone: [
          { required: true, message: "办公电话不能为空", trigger: "blur" },
        ],
        linkMan: [
          { required: true, message: "联系人姓名不能为空", trigger: "blur" },
        ],
        linkTel: [
          {
            required: true,
            message: "联系人办公电话不能为空",
            trigger: "blur",
          },
          {
            pattern: /^(0\d{2,3}-)?\d{7,8}$/g,
            message: "请填写正确的联系人办公电话",
            trigger: "change",
          },
        ],
        linkPhone: [
          {
            required: true,
            message: "联系人手机号码不能为空",
            trigger: "blur",
          },
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: ["blur", "change"],
          },
        ],

        email: [
          {
            type: "email",
            message: "请输入正确的邮箱地址",
            trigger: ["blur", "change"],
          },
        ],
        factRegprin: [
          {
            pattern: /^\d+(\.\d{1,2})?$/,
            message: "请输入正确的实收资金(万元)",
            trigger: ["blur", "change"],
          },
        ],
        regprin: [
          {
            pattern: /^\d+(\.\d{1,2})?$/,
            message: "请输入正确的请输入注册资本(万元)",
            trigger: ["blur", "change"],
          },
        ],
        assets: [
          {
            pattern: /^\d+(\.\d{1,2})?$/,
            message: "请输入正确的企业净资产",
            trigger: ["blur", "change"],
          },
        ],
        fax: [
          {
            pattern: /^(?:\d{3,4}-)?\d{7,8}(?:-\d{1,6})?$/,
            message: "请输入正确的传真号码",
            trigger: ["blur", "change"],
          },
        ],
      },
      userId: null,
      roleIds: [],
      active: 0,
      dateRangePicker: {
        disabledDate(time) {
          return time.getTime() > Date.now();
        },
      },
    };
  },
  created() {
    this.loadUserInfo();
    this.getDeptTree();
  },
  methods: {
    /** 查询部门下拉树结构 */
    getDeptTree() {
      deptTreeSelect().then((response) => {
        this.deptOptions = response.data;
      });
    },
    previous() {
      this.active--;
    },
    next() {
      // console.log("next", this.active);
      // console.log("company", this.$store.state.user);
      // if (this.active++ > 2) this.active = 0;
      switch (this.active) {
        case 0:
          this.submitAuthRoleForm();
          break;
        case 1:
          this.submitCompanyForm();
          break;
        case 2:
          this.submitCompanyForm();
          break;
      }
    },
    download() {
      let a = document.createElement("a");
      a.href = `/static/黑龙江省建筑起重机械安全监督管理系统使用说明.docx`;
      a.download = "黑龙江省建筑起重机械安全监督管理系统使用说明.docx";
      a.click();
    },
    loadUserInfo() {
      getHomeUserInfo().then((response) => {
        this.userInfo = response.data;
        if (this.userInfo.avatar && this.userInfo.avatar != "") {
          this.userInfo.avatar =
            process.env.VUE_APP_BASE_API + this.userInfo.avatar;
        } else {
          this.userInfo.avatar = require("@/assets/images/profile.jpg");
        }
        if (response.data.roleIds.length === 0) {
          if (
            response.data.remark.indexOf("AS") > -1 ||
            response.data.remark.indexOf("AD") > -1
          ) {
            //显示不同dialog，主管部门更新用户部门及授权角色；企业单位通过页面授权角色且更新企业信息
            this.deptOpen = true;
          } else {
            this.open = true;
          }
          this.userId = response.data.userId;
        }
      });
    },
    submitForm() {
      this.$confirm("请确认信息是否无误，确定进入系统?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$store.dispatch("GetInfo").then(() => {
            location.href = "/index";
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "请核对信息",
          });
        });
    },
    /** 提交按钮 */
    submitCompanyForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          // const userId = this.userId;
          // const roleIds = this.form.roleIds.join(",");
          // console.log('submit', userId, roleIds)
          // console.log('sss',this.$store.getters.permission_routes);
          // this.$confirm('请确认信息是否无误，确认点击下一步?', '提示', {
          //   confirmButtonText: '确定',
          //   cancelButtonText: '取消',
          //   type: 'warning'
          // }).then(() => {
          updateCompany(this.form).then((response) => {
            this.active++;
            this.$message({
              type: "success",
              message: "企业信息提交成功",
            });
          });
          // }).catch(() => {
          //   this.$message({
          //     type: 'info',
          //     message: '请继续核对信息'
          //   });
          // });
        }
      });
    },
    submitAuthRoleForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          const userId = this.userId;
          const roleIds = this.form.roleIds.join(",");
          // console.log('submit', userId, roleIds)
          // console.log('sss',this.$store.getters.permission_routes);
          this.$confirm("请确认企业类型是否无误，点击确认进行下一步?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
            .then(() => {
              unPermissionAuthRole({ userId: userId, roleIds: roleIds }).then(
                (response) => {
                  this.active++;
                  this.$message({
                    type: "success",
                    message: "授权成功",
                  });
                  if (this.$store.state.user.company != null) {
                    this.form = this.$store.state.user.company;
                  }
                }
              );
            })
            .catch(() => {
              this.$message({
                type: "info",
                message: "请核对信息",
              });
            });
        }
      });
    },
    submitDeptAuthRoleForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.$confirm(
            "请确认主管部门所在地是否无误，点击确认进入系统?",
            "提示",
            {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
            }
          )
            .then(() => {
              if (this.form.deptId === 100) {
                this.$message({
                  type: "error",
                  message: "禁止选择顶级部门",
                });
                return;
              }
              unPermissionDeptAuthRole({
                userId: this.userId,
                deptId: this.form.deptId,
                roleIds: 109,
              }).then((response) => {
                this.$message({
                  type: "success",
                  message: "授权成功",
                });
                if (this.$store.state.user.company != null) {
                  this.form = this.$store.state.user.company;
                }

                this.$store.dispatch("GetInfo").then(() => {
                  location.href = "/index";
                });
              });
            })
            .catch(() => {
              this.$message({
                type: "info",
                message: "请核对信息",
              });
            });
        }
      });
    },
  },
};
</script>
<style>
.home-user-info-container {
  padding: 10px 0;
}
.home-user-info-container .el-card__body {
  padding: 10px 10px 5px 10px;
}
.home-user-info-container .div-avatar {
  padding: 5px;
  text-align: center;
}
.home-user-info-container .home-user-avatar {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  overflow: hidden;
}
.home-user-info-container .user-info-header {
  font-size: 16px;
  padding: 12px 0;
  color: #5a5e66;
}
.home-user-info-container .user-info-header a {
  color: #409eff;
  padding-left: 10px;
}
.home-user-info-container .user-info-detail {
  display: block;
  font-size: 12px;
  color: #6a6b6e;
}
.home-user-info-container .user-info-detail i {
  margin-right: 15px;
}
.home-user-info-container .user-info-detail i span {
  color: #909399;
  padding-left: 5px;
}
</style>
